package com.iwomy.secureplat.platform.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class JsonUtil {

    public static boolean containsKey(Object object, String key) {
        if(object instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) object;
            for (Map.Entry<String, Object> entry: jsonObject.entrySet()) {
                Object o = entry.getValue();
                if(StrUtil.equals(entry.getKey(), key)) {
                    return true;
                }
                if(o instanceof String || o instanceof Integer || o instanceof Boolean) {
                    // 值
                } else if(containsKey(o, key)){
                    return true;
                }
            }
        }
        if(object instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) object;
            for(int i = 0; i < jsonArray.size(); i ++) {
                if (containsKey(jsonArray.get(i), key)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static List<Object> getValueByKey(Object object, String key) {
        List<Object> result = new ArrayList<>();
        if(object instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) object;
            for (Map.Entry<String, Object> entry: jsonObject.entrySet()) {
                Object o = entry.getValue();
                if(ObjectUtil.isNotEmpty(o)) {
                    if (o instanceof String || o instanceof Integer || o instanceof Boolean) {
                        if (StrUtil.equals(entry.getKey(), key)) {
                            result.add(o);
                        }
                        // 值
                    } else {
                        result.addAll(getValueByKey(o, key));
                    }
                }
            }
        }
        if(object instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) object;
            for(int i = 0; i < jsonArray.size(); i ++) {
                result.addAll(getValueByKey(jsonArray.get(i), key));
            }
        }
        return result;
    }
}
